package com.isesol.ime.service;

import com.alibaba.fastjson.*;
import com.google.common.collect.*;
import com.isesol.arch.common.mq.*;
import com.isesol.arch.common.utils.*;
import com.isesol.ime.*;
import com.isesol.ime.dal.mapper.*;
import lombok.extern.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.util.*;

/**
 * 订阅反馈
 *
 * @author peter zhang
 */
@Component
@Slf4j
public class SubFeedbackService{

	@Resource
	SubscriptionFeedbackMapper subscriptionFeedbackMapper;

	@Resource
	DownloadService eventService;

	@Resource
	SendOrderService sendOrderService;

	@Autowired(required = false)
	MsgSender msgSender;

	/**
	 * 订阅补偿
	 *
	 * @param machineId
	 */
	public void compensate(String machineId) throws Exception{

		// 未反馈记录数
		long unFeedbackCount = subscriptionFeedbackMapper.unFeedbackCount(machineId);
		// 没有，直接不补偿
		if (0 == unFeedbackCount){

			log.info("无须补偿,machineId={}",machineId);

			return;
		}

		Long timeUnFeedbackSubId  = subscriptionFeedbackMapper.findUnFeedbackSubIdByRuleTye(machineId, "time");
		Long eventUnFeedbackSubId = subscriptionFeedbackMapper.findUnFeedbackSubIdByRuleTye(machineId, "event");

		if (null != timeUnFeedbackSubId){
			log.info("补偿频率报文,machineId={}",machineId);

			sendOrder("subscrData", String.valueOf(timeUnFeedbackSubId), machineId);

		}

		if (null != eventUnFeedbackSubId){

			log.info("补偿事件报文,machineId={}",machineId);

			sendOrder("eventData", String.valueOf(eventUnFeedbackSubId), machineId);

		}

	}

	public void sendOrder(String path, String ids, String machineId) throws Exception{

		Map    infoMap               = Maps.newHashMap();
		String configFileDownloadUrl = PropertyFileUtil.get(Constant.CONFIG_FILE_DOWNLOAD_URL);

		infoMap.put("downloadUrl", configFileDownloadUrl + ids);
		infoMap.put("path", path);
		infoMap.put("id", String.valueOf(ids));
		Map reqMap = Maps.newHashMap();
		reqMap.put("orderData", JSON.toJSONString(infoMap));
		reqMap.put("orderType", "91");
		reqMap.put("frequence", "1");
		reqMap.put("switchs", "on");
		reqMap.put("destination1", machineId);

		sendOrderService.sendOrder(JSON.toJSONString(infoMap),
		                           Constant.DOWNLOAD_FEEDBACK + "|" + ids,
		                           "91", 7, "1", "on",
		                           machineId);

	}

}
